# -*- encoding: utf-8 -*- 
from datetime import datetime, timedelta
from openerp import SUPERUSER_ID
from openerp import api, fields, models, _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import UserError
from openerp.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
import os
import shutil
class fhcode_tb_table(models.Model):
    _name = 'fhcode.tb_table'
    _description = u'对象表'
    _rec_name='name'
    _order='create_date DESC'		
    def get_employee(self):
        obj = self.env['hr.employee']
        idsobj = obj.search([('user_id','=',self.env.user.id)])
        print('-------------------------------------')		
        print(self.env.user.id)		
        #print(ids)	
        res = idsobj.read()
        print(res)					
        return res and res[0]['id'] or 0				
    name= fields.Char(u'英文',readonly=False,required=False,translate=False)
    description= fields.Char(u'中文',readonly=False,required=False,translate=False)
    rec_name= fields.Char(u'显示内容',readonly=False,required=False,translate=False)
    orde= fields.Char(u'排序',readonly=False,required=False,translate=False)
    inherit= fields.Char(u'继承对象',readonly=False,required=False,translate=False)
	
    #name002= fields.Char(u'_page',readonly=False,required=False,translate=False)	
    #name003= fields.Char(u'_depend',readonly=False,required=False,translate=False)	
    fhzbao= fields.Boolean(u'带有子表',)
    fhdyin= fields.Boolean(u'带有打印',)
	
    modle_id = fields.Many2one('fhcode.tb_modle', string=u'模块')  
					   
    FDisable=fields.Selection([('0',u'启用'),('1',u'停用')],u'是否停用',readonly=False,required=False,translate=False)
    order_line = fields.Many2many("fhcode.tb_base",'fhcode_tbtable_tbbase_rel', 'uid', 'gid', string=u'基本字段',)#fields.One2many('fhcode.tb_tableline', 'pay_id', string='Order Lines', copy=True)

    @api.multi
    def print_quotation(self):
	    #取模块的路径,没有则创建
        path=self.modle_id.fpath
        path2=self.modle_id.fpath2		
        t=os.path.exists(path)
        if(t==False):
            self.os_mkdir(path)
			
			
			
        oldname= path2+"\\Template\\__init__.py"
        newname=path+"\\__init__.py"
		
		
        t=os.path.exists(newname)		
        if(t==False):
			#self.os_mkdir(path)		
            shutil.copyfile(oldname,newname)
			
			
        oldname= path2+"\\Template\\__manifest__.py"
        newname=path+"\\__manifest__.py"
		
		
        t=os.path.exists(newname)		
        if(t==False):
			#self.os_mkdir(path)		
            shutil.copyfile(oldname,newname)

		#无子表
        if(self.fhzbao==False):
            self.os_readlines(path2+"\\Template\\Template_view.xml",path+"\\"+self.modle_id.fname+"_"+self.name+".xml")
            self.os_readlines_py(path2+"\\Template\\Template.py",path+"\\"+self.modle_id.fname+"_"+self.name+".py")
		#有子表
        if(self.fhzbao==True):		
            self.os_readlines(path2+"\\Template\\Template_view002.xml",path+"\\"+self.modle_id.fname+"_"+self.name+".xml")
            self.os_readlines_py(path2+"\\Template\\Template002.py",path+"\\"+self.modle_id.fname+"_"+self.name+".py")		
		
        #打印报表
        if(self.fhdyin==True):			
            pathreport=self.modle_id.fpath+"\\report"
            pathreport2=self.modle_id.fpath2+"\\Template\\report"		
            t=os.path.exists(pathreport)
            if(t==False):
                self.os_mkdir(pathreport)		
			#self.os_readlines(path2+"\\Template\\Template_view.xml")
            oldname= pathreport2+"\\__init__.py"
            newname=pathreport+"\\__init__.py"
			
            t=os.path.exists(newname)		
            if(t==False):		
                shutil.copyfile(oldname,newname)			

            oldname= pathreport2+"\\sale_report.xml"
            newname=pathreport+"\\"+self.modle_id.fname+"_"+self.name+"_report.xml"
			#shutil.copyfile(oldname,newname)
            self.os_readlineswork(oldname,newname)			
		
            oldname= pathreport2+"\\sale_report_templates.xml"
            newname=pathreport+"\\"+self.modle_id.fname+"_"+self.name+"_report_templates.xml"
			#shutil.copyfile(oldname,newname)
            self.os_readlineswork(oldname,newname)					
					
		#工作流
        if(1==1):		
            self.os_readlineswork(path2+"\\Template\\TB_workflow.xml",path+"\\"+self.modle_id.fname+"_"+self.name+"_workflow.xml")		
        return True

    def os_mkdir(self,path):

        os.mkdir(path)      
        return True

		
    def os_readlineswork(self,path,path2):

        # 打开文件
        fo = open(path, "r",encoding='UTF-8')
        print ("文件名为: ", fo.name)
        print ("文件名为2: ", self.description)
        print ("文件名为3: ", self.modle_id.fname+"."+self.name)
		
		
        fields=self.os_fields()
        #print(fields)

        fieldsII=self.os_fieldsII()
        #print(fields)		
        lineST=""
        for line in fo.readlines():                          #依次读取每行  
            #line = line.strip()                             #去掉每行头尾空白
            line=line.replace("FHsaasMK",self.modle_id.fname);		
            line=line.replace("FHsaasTB",self.name);  			
            line=line.replace("FHsaasZW",self.description);            					
            #print(line)			
            lineST=lineST+line+""			
 
        # 关闭文件
        #print(lineST)


        fo = open(path2, "w",encoding='UTF-8')
        #print "文件名为: ", fo.name
        #str = "菜鸟教程"
        fo.write(lineST)
        fo.close()      
        return True		
		
		
		
    def os_readlines(self,path,path2):

        # 打开文件
        fo = open(path, "r", encoding='UTF-8')
        print ("文件名为: ", fo.name)
        print ("文件名为2: ", self.description)
        print ("文件名为3: ", self.modle_id.fname+"."+self.name)
		
		
        fields=self.os_fields()
		
		
		
		
        #print(fields)

        fieldsII=self.os_fieldsII()
		
        #fieldsII = sorted(fieldsII, key=lambda l: l[0].id)		
		
		
		
        #print(fields)		
        lineST=""
        for line in fo.readlines():
            print(str(line))
            if str(line) != False:               
                line=line.replace("FHsaasMK",self.modle_id.fname);		
                line=line.replace("FHsaasTB",self.name);  			
                line=line.replace("FHsaasZW",self.description);            			
                line=line.replace("<fieldsfrom>",fieldsII);
                line=line.replace("<fields>",fields);			
                #print(line)			
                lineST=lineST+line+""			
 
        # 关闭文件
        #print(lineST)


        fo = open(path2, "w",encoding='UTF-8')
        #print "文件名为: ", fo.name
        #str = "菜鸟教程"
        fo.write(lineST)
        fo.close()      
        return True
		
    def os_fields(self):
        ls=""
        res = sorted(self.order_line, key=lambda l: l[0].id)		
        for line in res:
            if(ls==""):			
                ls=ls+'<field name="'+line.fen+'" />\n'			
            else:			
                ls=ls+'                  '+'<field name="'+line.fen+'" />\n'			
        #os.mkdir(path)      
        return ls		
		
		
    def os_fieldsII(self):
        ls=""
		
        res = sorted(self.order_line, key=lambda l: l[0].id)			
        for line in res:
		
            if(line.ftype!="many2many"):		
                if(ls==""):
                    if(line.required==True):			
                        ls=ls+'<field name="'+line.fen+'"  required="1" />\n'	
                    else:			
                        ls=ls+'<field name="'+line.fen+'" />\n'	
                        
                else:
                
                    if(line.required==True):
                        ls=ls+'						'+'<field name="'+line.fen+'" required="1" />\n'
                    else:
                        ls=ls+'						'+'<field name="'+line.fen+'" />\n'	


            if(line.ftype=="many2many"):		
                if(ls==""):
                    if(line.required==True):			
                        ls=ls+'<field name="'+line.fen+'"  widget="many2many_tags" required="1" />\n'	
                    else:			
                        ls=ls+'<field name="'+line.fen+'" widget="many2many_tags"  />\n'

            
                else:
            
                    if(line.required==True):
                        ls=ls+'						'+'<field name="'+line.fen+'" required="1" widget="many2many_tags"   />\n'
                    else:
                        ls=ls+'						'+'<field name="'+line.fen+'"  widget="many2many_tags" />\n'	


						
        #os.mkdir(path)      
        return ls
		
		
		
    def os_readlines_py(self,path,path2):

        # 打开文件
        fo = open(path, "r",encoding='UTF-8')
        print ("文件名为: ", fo.name)
        print ("文件名为2: ", self.description)
        print ("文件名为3: ", self.modle_id.fname+"."+self.name)
        fieldsII=self.os_fieldsII_py()
        print(fieldsII)		
        lineST=""
        for line in fo.readlines():                          #依次读取每行  
            #line = line.strip()                             #去掉每行头尾空白
            line=line.replace("FHsaasMK",self.modle_id.fname);		
            line=line.replace("FHsaasTB",self.name);
            line=line.replace("FHsaasZW",self.description);            			
            line=line.replace("FHSAAS_columns",fieldsII);
            '''line=line.replace("<fields>",fields.encode(encoding='UTF-8'));'''			
            print(line)			
            lineST=lineST+line+""			

        # 关闭文件
        #print(lineST)


        fo = open(path2, "w",encoding='UTF-8')
        fo.write(lineST)
        fo.close()      
        return True		
    def os_fieldsII_py(self):
        ls=""
		
        res = sorted(self.order_line, key=lambda l: l[0].id)			
		
        for line in res:
            if(line.ftype=="char"):		
                ls=ls+"    "+line.fen+"=fields.Char(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="integer"):		
                ls=ls+"    "+line.fen+"=fields.Integer(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="float"):		
                ls=ls+"    "+line.fen+"=fields.Float(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="boolean"):		
                ls=ls+"    "+line.fen+"=fields.Boolean(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	
				
            if(line.ftype=="selection"):		
                ls=ls+"    "+line.fen+"=fields.Selection([('0',u'KEY1'),('1',u'KEY2')],u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	
				
            if(line.ftype=="date"):		
                ls=ls+"    "+line.fen+"=fields.Date(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	


            if(line.ftype=="datetime"):		
                ls=ls+"    "+line.fen+"=fields.Datetime(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="text"):		
                ls=ls+"    "+line.fen+"=fields.Text(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="function"):		
                ls=ls+"    "+line.fen+"=fields.Text(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="many2one"):		
                ls=ls+"    "+line.fen+"=fields.Many2one('"+line.many2oneII+"',u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="many2many"):		
                ls=ls+"    "+line.fen+"=fields.Many2many('"+line.many2manyII+"','many2man_"+self.modle_id.fname+"_"+self.name+"_"+line.fen+"_rel', 'uid', 'gid', u'"+line.fname+"',)"+"\n"
				
				
        return ls		
		
	
    @api.model		
    @api.model		
    def action_funproved0(self):
        #context = context or {}
        t=fields.datetime.now()
        #huid=self.get_employee(cr,uid,context)
        self.write({'Fstatus':'wait_prove','FAdddate':t})       
        return True
		
    @api.model		
    def action_funproved(self):
        #context = context or {}
        t=fields.datetime.now()
        #huid=self.get_employee(cr,uid,context)
        self.write({'Fstatus':'proved','FAdddate':t})       
        return True		
    @api.model		
    def create(self, vals):
        result = super(fhcode_tb_table, self).create(vals)	
        return result
    @api.multi		
    def write(self, values):
	    
        result = super(fhcode_tb_table, self).write(values)		
		
        return result
    @api.multi
    def unlink(self):
	
        return super(fhcode_tb_table, self).unlink()
    @api.multi
    def copy(self, default=None):
        return super(fhcode_tb_table, self).copy(default)
    @api.multi
    def search(self, args, offset=0, limit=None, order=None, context=None, count=False):
        domain =None		
        domain = [('Fstatus', '=', '0')]		
        return super(fhcode_tb_table, self).search(args, offset=offset, limit=limit, order=order, count=count)		
fhcode_tb_table() #对象定义结束
class fhcode_tb_tableline(models.Model):
    _name = 'fhcode.tb_tableline'
    _description = u'详细信息'
    #_rec_name='FClass'
    def get_employee(self, cr, uid, context={}):
        obj = self.pool.get('hr.employee')
        ids = obj.search(cr, uid, [('user_id','=',uid)])
        res = obj.read(cr, uid, ids, ['id','name'], context)
        return res and res[0]['id'] or 0
    pay_id=fields.Many2one('fhcode.tb_table',u'fhcode_tb_table',required=True, ondelete='cascade', index=True, copy=False)
    fkec=fields.Many2one('fhcode.tb_base',u'选择字段',)
    fkecsl=fields.Char(u'备注',readonly=False,required=False,translate=False)
    FAddperson =fields.Many2one('hr.employee',u'添加人',readonly=False,required=False,translate=False)
    FConsultant=fields.Many2one('hr.employee',u'班主任',readonly=False,required=False,translate=False)					   
    FAdddate= fields.Datetime(u'添加日期',readonly=False,required=False,translate=False)
    Fstatus=fields.Selection([('0',u'未分班'),('1',u'已分班')],u'是否分班',readonly=False,required=False,translate=False)					   
    FDisable=fields.Selection([('0',u'启用'),('1',u'停用')],u'是否停用',readonly=False,required=False,translate=False) 
	
fhcode_tb_tableline() #对象定义结束
